﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.Supervise.Model;
using HZ.Supervise.IBLL;
using System.Data.Sql;
using System.Data;
using System.Collections;
using System.Drawing;


public partial class TotalDrugs_chartTest : BasePage
{
    public TotalDrugs_chartTest()
    { }
    protected void Page_Load(object sender, EventArgs e)
    {
        QueryControl1.OnQueryClick += new EventHandler(QueryControl1_OnQueryClick);
        if (!IsPostBack)
        {
            ViewState["query"] = URLUtil.GetSuperviseQueryFromURL(Request);
            QueryControl1.BindDataPre((SuperviseQuery)ViewState["query"]);
            BindData();//绑定数据
            QueryControl1.BindSort(gvwInfo);
        }
    }

    void QueryControl1_OnQueryClick(object sender, EventArgs e)
    {
        AspNetPager1.CurrentPageIndex = 1;
        ViewState["query"] = QueryControl1.UpdateQueryFromValue((SuperviseQuery)ViewState["query"]);
        BindData();
    }

    protected void BindData()
    {
        int t = 0;
        HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();
        ie.QueryObject = new HZ.Supervise.Model.QueryObject()
        {
            GroupField = GroupByField.OrderID,
            Query = (SuperviseQuery)ViewState["query"],
            GroupSelectField = (ShowColumns.ShowColumn == null) ? GroupFields.PurchaseAmountTotal : ShowColumns.ShowColumn.GroupFields,
            SortField = QueryControl1.SortField == "" ? "OrderID ASC" : QueryControl1.SortField
        };

        System.Data.DataTable dt = ie.ExecutePage(AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out t);

        AspNetPager1.RecordCount = t;
        gvwInfo.PageSize = AspNetPager1.PageSize;
        gvwInfo.AutoGenerateColumns = false;
        GridViewUtil.AdjustGridView(gvwInfo, dt);
        gvwInfo.DataSource = dt;
        gvwInfo.DataBind();
        //bindchart(dt);
        //setChart(dt);
        SetColumnVisible();
    }

    /*private void getPic(DataTable dt)
    {
        Chart1.Series.Clear();
        Series Series1 = new Series();
        Chart1.Series.Add(Series1);

        if (dt == null)
        {


            Chart1.Series["Series1"].ChartType = SeriesChartType.Pie;
            Chart1.Series["Series1"]["PieLabelStyle"] = "Outside";
            Chart1.Series["Series1"]["PieLineColor"] = "Blue";
            Chart1.Series["Series1"].Color = Color.Green;                //线条颜色
            Chart1.Series["Series1"].BorderWidth = 2;                    //线条宽度
            Chart1.Series["Series1"].ShadowOffset = 1;                   //阴影宽度
            Chart1.Series["Series1"].IsVisibleInLegend = true;           //是否显示数据说明
            Chart1.Series["Series1"].IsValueShownAsLabel = true;        //线条上是否给吃数据的显示
            Chart1.Series["Series1"].MarkerStyle = MarkerStyle.Triangle;   //线条上的数据点标志类型
            Chart1.Series["Series1"].MarkerSize = 2;
            Chart1.Titles.Clear();

            Chart1.Titles.Add("aaaaaaaaaa");
            Chart1.Titles.Add("bbbbbbbbbbbbb");
            Font font = new Font("宋体", 10, FontStyle.Bold);
            Font fonts = new Font("宋体", 10, FontStyle.Regular);
            Chart1.Titles[0].Font = font;
            Chart1.Titles[1].Font = fonts;
            Chart1.ChartAreas["ChartArea1"].BackGradientStyle = GradientStyle.TopBottom;
            Chart1.ChartAreas["ChartArea1"].BackSecondaryColor = Color.Azure;
            Chart1.ChartAreas["ChartArea1"].AxisX.LineColor = Color.Blue;
            Chart1.ChartAreas["ChartArea1"].AxisY.LineColor = Color.Blue;

        }
        else
        {
            ArrayList jkycj = new ArrayList();
            ArrayList zbsl = new ArrayList();
            ArrayList tym = new ArrayList();

            foreach (DataRow row in dt.Rows)
            {
                jkycj.Add(row["ordername"].ToString());
                zbsl.Add(Convert.ToDouble(row["totalAmount"]));
                tym.Add(row["hospitalname"].ToString());
            }
            try
            {
                Chart1.Series["Series1"].ChartType = SeriesChartType.Pie;
                Chart1.Series["Series1"]["PieLabelStyle"] = "Outside";
                Chart1.Series["Series1"]["PieLineColor"] = "Blue";
                Chart1.Series["Series1"].Color = Color.Green;                //线条颜色
                Chart1.Series["Series1"].BorderWidth = 2;                    //线条宽度
                Chart1.Series["Series1"].ShadowOffset = 1;                   //阴影宽度
                Chart1.Series["Series1"].IsVisibleInLegend = true;           //是否显示数据说明
                Chart1.Series["Series1"].IsValueShownAsLabel = true;        //线条上是否给吃数据的显示
                Chart1.Series["Series1"].MarkerStyle = MarkerStyle.Triangle;   //线条上的数据点标志类型
                Chart1.Series["Series1"].MarkerSize = 2;
                //Chart1.Scale
                double sum = 0;
                string[] xval = new string[jkycj.Count];
                string[] zval = new string[jkycj.Count];
                double[] yval = new double[zbsl.Count];
                string[] xvals = new string[jkycj.Count];
                double[] yvals = new double[zbsl.Count];
                for (int i = 0; i < jkycj.Count; i++)
                {
                    string company = jkycj[i].ToString().Trim();

                    if (company.Length > 6)
                    {
                        company = company.Substring(0, 6) + "...";
                    }
                    zval[i] = jkycj[i].ToString().Trim();
                    xval[i] = company;
                    yval[i] = (double)zbsl[i];
                    //Chart1.Series["Series1"].Points.DataBindXY(xval, yval);
                    sum += yval[i];
                    Chart1.Series["Series1"].Points.AddXY(xval[i], yval[i]);
                    //Chart1.Series["Series1"].ToolTip = zval[i];
                    //Chart1.Series["Series1"].Legend = pp[i].ToString().Trim();
                    //string ggg = xval[i] + " " + "中标数：" + yval[i] + "占：";
                    //Chart1.Legends["Legend1"].Title= ggg[i].ToString();
                    //Chart1.Series["Series1"].Label = " #VALX中标数：#VALY 占：#PERCENT{P1}";
                }
                Chart1.Titles.Clear();

                Chart1.Titles.Add("cccc");
                Chart1.Titles.Add("dddddd");
                Font font = new Font("宋体", 10, FontStyle.Bold);
                Font fonts = new Font("宋体", 10, FontStyle.Regular);
                Chart1.Titles[0].Font = font;
                Chart1.Titles[1].Font = fonts;
                //double[] yval = dt.Rows.Add("");
                //double[] yval = { 2, 6, 4, 5, 3 };

                //string[] xval = { "广西南宁药业", "哈药", "南京长奥", "山东鲁南", "石药" };

                //Chart1.Series["Series1"].BackGradientStyle = GradientStyle.None;
                //Chart1.Invalidate();
                //Chart1.Series["Series1"].Points.DataBindXY(xval, yval);
                Chart1.Series["Series1"].Label = " #VALX中标数：#VALY 占：#PERCENT{P1}";
                //Chart1.Series["Series1"].Legend = "abc";
                //Chart1.Series["Series1"].LegendText = "aa";



                Chart1.ChartAreas["ChartArea1"].BackImage = "..//images//bg_1.jpg";   // Directory.GetCurrentDirectory() + "\\images\\backs.jpg";
                //Chart1.ChartAreas["ChartArea1"].BackImage=Application.LocalUserAppDataPath.
                Chart1.ChartAreas["ChartArea1"].BackGradientStyle = GradientStyle.TopBottom;
                Chart1.ChartAreas["ChartArea1"].BackSecondaryColor = Color.Azure;
                Chart1.ChartAreas["ChartArea1"].AxisX.LineColor = Color.Blue;
                Chart1.ChartAreas["ChartArea1"].AxisY.LineColor = Color.Blue;
            }
            catch (Exception exe)
            {
                exe.ToString();
            }
        }
    }

    //调用该方法生成柱状图
    private void bindchart(DataTable dt)
    {
        //获取一个DataTable,具体函数略...
        
        if (dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                //遍历DataTable为每条记录生成一个柱状
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //创建对象
                    ColumnChart mychart = new ColumnChart();
                    //设置柱子宽度
                    mychart.MaxColumnWidth = 48;
                    //颜色
                    mychart.Fill.Color = Color.FromName(this.myColor[i]);
                    //在柱子上显示数量
                    mychart.DataLabels.Visible = true;
                    //数量的字体
                    mychart.DataLabels.Font = new Font("Verdana", 14);
                    //添加
                    mychart.Data.Add(new ChartPoint("", float.Parse(dt.Rows[i]["num"].ToString())));
                    //备注
                    mychart.Legend = dt.Rows[i]["name"].ToString();
                    this.chart.Charts.Add(mychart);
                }
                //辅助设置
                //背景色
                Chart1.Background.Color = Color.FromArgb(165, 0, 16);
                Chart1.YAxisFont.ForeColor = Color.FromArgb(165, 0, 16);
                Chart1.XAxisFont.ForeColor = Color.FromArgb(165, 0, 16);
                //内部线条
                Chart1.Border.Color = Color.FromArgb(200, 200, 200);
                //边框样式
                Chart1.BorderStyle = BorderStyle.None;
                //y最大值
                double max = double.Parse(dt.Compute("MAX(num)", "").ToString());
                //递增值
                int intv = 2;

                //数量小于16的情况
                if (max < 16)
                {
                    max = 16;
                }
                //大于16的情况
                else
                {
                    intv = int.Parse(Math.Ceiling(max / 8).ToString());
                    max += intv;
                }

                //设置Y轴终点值
                Chart1.YCustomEnd = int.Parse(max.ToString());
                //y递增值
                Chart1.YValuesInterval = intv;

                //生成
                this.Chart1.RedrawChart();
            }
        }
    }*/

    protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
    {
        BindData();
    }
    protected void gvwInfo_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //按企业查看
        if (e.CommandName == "DirectByCom")
        {
            //设置分组查询字段GroupSelectField
            if (ShowColumns.ShowColumn == null)
            {
                ShowColumns.ShowColumn = new ShowColumns();
                ShowColumns.ShowColumn.GroupFields = GroupFields.DistributeCountTotal | GroupFields.DistributeRate | GroupFields.PurchaseCountTotal | GroupFields.WareHouseCountTotal;
            }

            string sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];
            query.OrderID = e.CommandArgument.ToString();
            Session[sessionid] = query;

            string url = System.Configuration.ConfigurationManager.AppSettings["CompanyID_PS"];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));

        }

        //按药品查看
        if (e.CommandName == "DierectByDrug")
        {
            //设置分组查询字段GroupSelectField
            if (ShowColumns.ShowColumn == null)
            {
                ShowColumns.ShowColumn = new ShowColumns();
                ShowColumns.ShowColumn.GroupFields = GroupFields.DistributeCountTotal | GroupFields.DistributeRate | GroupFields.PurchaseCountTotal | GroupFields.WareHouseCountTotal;
            }


            string sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];
            query.OrderID = e.CommandArgument.ToString();
            Session[sessionid] = query;

            string url = System.Configuration.ConfigurationManager.AppSettings["ProcureCatalogID"];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }

        if (e.CommandName == "DierectByDetail")
        {
            if (ShowColumns.ShowColumn == null)
            {
                ShowColumns.ShowColumn = new ShowColumns();
                ShowColumns.ShowColumn.GroupFields = GroupFields.DistributeCountTotal | GroupFields.DistributeRate | GroupFields.PriceAvg | GroupFields.PurchaseAmountTotal | GroupFields.PurchaseCountTotal | GroupFields.WareHouseAmountTotal | GroupFields.WareHouseCountTotal | GroupFields.WareHouseRate;

            }

            string sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];
            query.OrderID = e.CommandArgument.ToString();
            Session[sessionid] = query;
            string url = System.Configuration.ConfigurationManager.AppSettings["HosComDrugs"];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }
    }


    #region   数据准备



    /// <summary>
    /// 屏蔽相关查询连接
    /// </summary>
    private void SetColumnVisible()
    {
        gvwInfo.Columns[1].Visible = false;
        if (!string.IsNullOrEmpty(QueryControl1.ProcureCatalogID))
        {
            foreach (GridViewRow row in gvwInfo.Rows)
            {
                row.FindControl("lbnDrug").Visible = false;
            }
        }
        if (!string.IsNullOrEmpty(QueryControl1.CompanyID_PS))
        {
            foreach (GridViewRow row in gvwInfo.Rows)
            {
                row.FindControl("lbnCom_PS").Visible = false;
            }
        }
        //if (!string.IsNullOrEmpty(txtHospitalId.Value))
        //{
        //    foreach (GridViewRow row in gvwInfo.Rows)
        //    {
        //        row.FindControl("lbnHos").Visible = false;
        //    }
        //}
    }

    #endregion
    //protected void ddlOther_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    string stkey = "";
    //    string sessionid = string.Empty;
    //    GridViewRow row = (GridViewRow)((Control)sender).Parent.Parent;
    //    DropDownList ddl = (DropDownList)row.FindControl("ddlOther");
    //    stkey = ddl.SelectedValue;
    //    if (stkey != "")
    //    {
    //        sessionid = Guid.NewGuid().ToString();
    //        SuperviseQuery query = (SuperviseQuery)ViewState["query"];
    //        query.OrderID = row.Cells[1].Text; //((LinkButton)row.FindControl("lbnHos")).CommandArgument;
    //        Session[sessionid] = query;
    //        string url = System.Configuration.ConfigurationManager.AppSettings[stkey];
    //        Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
    //    }
    //}

    /// <summary>
    /// 设置图表
    /// </summary>
    /// <param name="?"></param>
    private void setChart(System.Data.DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {
            this.ChartControl1.Visible = true;
            HZ.Supervise.Web.WebService.ChartConfig serChart = new HZ.Supervise.Web.WebService.ChartConfig();
            dt.TableName = "订单";
            serChart.DataSource = dt;

            if (ShowColumns.ShowColumn == null)
            {
                serChart.XName = "OrderName";
                serChart.YNames = "PurchaseAmountTotal";
            }
            else
            {
                string[] _columns = ShowColumns.ShowColumn.GroupFields.ToString().Split(',');
                serChart.XName = "OrderName";
                serChart.YNames = _columns[0];
            }

            serChart.ChartTypes = HZ.Supervise.Web.WebService.ChartType.PieChart;

            ChartControl1.webChart = serChart;
            ChartControl1.PageId = Guid.NewGuid().ToString();
            ChartControl1.EntranceChart();
        }
        else
        {
            ChartControl1.Visible = false;
        }
    }




}
